<script
	lang="ts"
	setup
>
import { sysuserResetPwdPut } from '@/api'
import EmptyModal from '@/components/EmptyModal.vue'
import type { FormInst, FormRules } from 'naive-ui'
import { ref } from 'vue'

interface IProps {
	show?: boolean
	data?: any
}

const emit = defineEmits(['update:show', 'update:list'])
const props = withDefaults(defineProps<IProps>(), {
	show: false
})

const formRef = ref<FormInst | null>(null)
const loading = ref(false)
const formData = ref({
	password: ''
})

const rules: FormRules = {
	password: [{
		required: true,
		message: '请输入新密码',
		trigger: ['blur', 'input']
	}]
}

function onCancel() {
	if (!loading.value) {
		emit('update:show', false)
		formData.value.password = ''
	}
}

async function onSubmit() {
	if (!formRef.value) return
	if (!props.data?.userId) {
		window.$message.error('用户ID不能为空')
		return
	}

	formRef.value.validate().then(async values => {
		console.log(values)
		loading.value = true
		const { code } = await sysuserResetPwdPut({
			userId: props.data.userId,
			password: formData.value.password
		})

		if (code === 200) {
			window.$message.success('密码重置成功')
			formData.value.password = ''
			emit('update:show', false)
			emit('update:list')
		}
	})
}
</script>

<template>
	<EmptyModal
		:show="show"
		preset="dialog"
		:width="500"
		title="重置密码"
		:maskClosable="false"
		:on-negative-click="onCancel"
		:on-close="onCancel"
		:on-positive-click="onSubmit"
		:positive-button-props="{ loading }"
	>
		<n-form
			ref="formRef"
			:model="formData"
			:rules="rules"
			label-placement="left"
			label-width="100"
		>
			<n-form-item
				label="用户名"
				path="password"
			>
				{{data.userName}}
			</n-form-item>
			<n-form-item
				label="新密码"
				path="password"
			>
				<n-input
					type="password"
					placeholder="请输入新密码"
					v-model:value="formData.password"
				/>
			</n-form-item>
		</n-form>
	</EmptyModal>
</template>
